package one.stand.controller;

import com.jmp.api.dto.BusinessCardSaveRequest;
import com.jmp.api.dto.CardShareRequest;
import com.jmp.api.dto.CardShareResponse;
import com.jmp.api.dto.CardVerifyExpiredRequest;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.*;
import com.jmp.feign.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.UserDto;
import one.stand.enums.LoginEnum;
import one.stand.mapper.BusinessCardPublicMapper;
import one.stand.mapper.IndustryMapperExt;
import one.stand.mapper.SeeRecordPublicMapper;
import one.stand.model.*;
import one.stand.request.BusinessCardRequest;
import one.stand.request.CallsPhoneRecordRequest;
import one.stand.response.BusinessCardResponse;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Objects;
import java.util.Random;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/businessCard")
@Api(description = "名片系列")
public class BusinessCardController {
    private Random rand = new Random();

    @Autowired
    private CrmFegin crmFegin;
    @Autowired
    private UserFegin userFegin;
    @Autowired
    private TemplateFeign templateFeign;
    @Autowired
    private SunCodeFeign sunCodeFeign;
    @Autowired
    private AccountFeign accountFeign;
    @Autowired
    private CardFeign cardFeign;
    @Autowired
    private RecordFeign recordFeign;

    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private BusinessCardPublicMapper businessCardPublicMapper;
    @Autowired
    private SeeRecordPublicMapper seeRecordPublicMapper;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private IndustryMapperExt industryMapperExt;

    @ApiOperation(value = "获取公司员工")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", required = true, paramType = "Integer"),
    })
    @PostMapping("getCompanyStaffList")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<Map<String, Object>> getCompanyStaffList(@RequestAttribute BusinessCardRequest request) {
        return crmFegin.getCompanyStaffList(request);
    }

    @ApiOperation(value = "修改用户名片欢迎语")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "welcomeSpeech", value = "欢迎语", required = true, paramType = "String"),
            @ApiImplicitParam(name = "shareSpeech", value = "分享语", required = true, paramType = "String"),
    })
    @PostMapping("updateCardWelcomeSpeech")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<Boolean> updateCardWelcomeSpeech(@RequestAttribute BusinessCardRequest request) {
        return crmFegin.updateCardWelcomeSpeech(request);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "员工名片ID", paramType = "Integer"),
    })
    @ApiOperation(value = "获取员工详细信息")
    @PostMapping("getCompanyUserInfo")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<BusinessCardModel> getCompanyUserInfo(@RequestAttribute BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = new BusinessCardModel();
        if (request.getCardId() != null) {
            model = businessCardPublicMapper.selectByPrimaryKey2(request.getCardId());
        } else if (request.getUserId() != null) {
            model = businessCardPublicMapper.select(new BusinessCardModel() {{
                setUserId(request.getUserId());
                setIsDel(0);
                setState(1);
            }});
            if (model == null) {
                model = new BusinessCardModel();
                UserDto userModel = userAdminService.get(request.getUserId());
                if (userModel != null) {
                    model.setName(userModel.getName());
                    model.setNickeName(userModel.getName());
                    model.setPhone(userModel.getPhone());
                    model.setLogo(userModel.getUserImg());
                }
            }
        } else if (request.getMyCardId() != null) {
            // crm端查询个人中心名片信息
            model = businessCardPublicMapper.selectByPrimaryKey2(request.getMyCardId());
            if (model != null) {
                model.setBrowsePhoto(seeRecordPublicMapper.getBrowsePhoto(model.getCardId()));
                BusinessCardModel businessCardModel = businessCardPublicMapper.selectCrmPersonalData(model.getCardId());
                if (businessCardModel != null) {
                    model.setPerfectRate(businessCardModel.getPerfectRate());
                    model.setPerfectRateRank(businessCardModel.getPerfectRateRank());
                    model.setYesterdayCustomerCount(businessCardModel.getYesterdayCustomerCount());
                    model.setYesterdayOrderCount(businessCardModel.getYesterdayOrderCount());
                    model.setYesterdaySeeCount(businessCardModel.getYesterdaySeeCount());
                }

            }
        }

        if (Objects.nonNull(model)) {
            AccountCompanyIdRequest accountCompanyIdRequest = AccountCompanyIdRequest.builder()
                    .companyId(model.getCompanyId())
                    .loginEnum(LoginEnum.USER)
                    .build();
            ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getCompanyIdDefaultIfNull(accountCompanyIdRequest);
            if (accountResponseResultModel.isSuccess()) {
                model.setWechatId(accountResponseResultModel.getData().getWechatId());
            }
            if (Objects.nonNull(model.getCardId())) {
                TemplateGet2Request getRequest = TemplateGet2Request.builder()
                        .templateType(TemplateApi.Type.ID_WECHAT_CARD)
                        .cardId(model.getCardId())
                        .build();
                ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get2(getRequest);
                model.setPhotoUrl(getResponseResultModel.isSuccess() ? getResponseResultModel.getData().getImageUrl() : null);
                getRequest = TemplateGet2Request.builder()
                        .templateType(TemplateApi.Type.ID_CRM_APP_CARD)
                        .cardId(model.getCardId())
                        .build();
                getResponseResultModel = templateFeign.get2(getRequest);
                model.setCardMoments(getResponseResultModel.isSuccess() ? getResponseResultModel.getData().getImageUrl() : null);
                model.setOneCompany(companyBaseService.isOneWechat(model.getCompanyId()));
            }
        }
        return ResultModel.success(model);
    }

    /**
     * crm小程序分享，废弃
     */
    @Deprecated
    @ApiOperation(value = "获取员工详细信息（中转）")
    @PostMapping("getCompanyUserInfoTransfer")
    public ResultModel<BusinessCardModel> getCompanyUserInfoTransfer(@RequestAttribute BusinessCardRequest request) {
        if (request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        return crmFegin.getCompanyUserInfo(request);
    }

    @ApiOperation(value = "添加通话记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "被拨打人名片id", required = true, paramType = "Integer"),
    })
    @PostMapping("addCallsRecord")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel addCallsRecord(@RequestAttribute CallsPhoneRecordRequest request) {
        RequestContext.User user = RequestContextHolder.getRequestContext().getUser();
        ResultModel resultModel = recordFeign.call(RecordCallRequest.builder().userId(user.getUserId()).cardId(request.getCardId()).build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success(true);
    }

    @ApiOperation(value = "获取成员信息")
    @PostMapping("getUserCard")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel getUserCard(@RequestAttribute BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = new BusinessCardModel();
        model.setUserId(request.getId().intValue());
        if (request.getUserId() != null) {
            model.setThumbsUserId(request.getUserId());
        } else {
            model.setThumbsUserId(request.getId().intValue());
        }
        model.setState(1);
        BusinessCardModel businessCardModel = businessCardPublicMapper.select(model);
        if (businessCardModel == null) {
            return ResultModel.fail("名片不存在");
        }
        BusinessCardResponse response = new BusinessCardResponse();
        BeanUtils.copyProperties(businessCardModel, response);

        BusinessCard businessCard = businessCardBaseService.getCustomer(businessCardModel.getCardId());
        response.setWxCode(businessCard.getWxCode());

        return ResultModel.success(response);
    }

    @ApiOperation(value = "修改名片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "名片id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "style", value = "名片样式", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "name", value = "姓名", paramType = "String"),
            @ApiImplicitParam(name = "phone", value = "电话", paramType = "String"),
            @ApiImplicitParam(name = "logo", value = "头像url", paramType = "String"),
            @ApiImplicitParam(name = "personalWx", value = "个人微信", paramType = "String"),
            @ApiImplicitParam(name = "companyWx", value = "公司微信", paramType = "String"),
            @ApiImplicitParam(name = "photo", value = "个人照片集合（1.png,2.png,3.png）", paramType = "String"),
            @ApiImplicitParam(name = "position", value = "职位", paramType = "String"),
            @ApiImplicitParam(name = "soundRecording", value = "个人录音", paramType = "String"),
            @ApiImplicitParam(name = "soundTime", value = "录音时长", paramType = "Integer"),
            @ApiImplicitParam(name = "email", value = "邮箱", paramType = "String"),
            @ApiImplicitParam(name = "briefIntroduction", value = "个人简介", paramType = "String"),
    })
    @PostMapping("updateCard")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<Boolean> updateCard(@RequestAttribute BusinessCardRequest request) {
        return userFegin.updateCard(request);
    }

    /**
     * @deprecated 2019/8/27 1.0.5
     */
    @ApiOperation(value = "得到名片海报")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "名片id", required = true, paramType = "Integer"),
    })
    @PostMapping("getCardPoster")
    @Deprecated
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel getCardPoster(@RequestAttribute BusinessCardRequest request) {
        return crmFegin.getCardPoster(request);
    }

    @ApiOperation(value = "创建名片")
    @PostMapping("createCard")
    @SecurityAuthCheck
    public ResultModel<Boolean> createCard(@RequestAttribute BusinessCardSaveRequest request) {
        AssertUtil.nonNull(request.getLicensePhotos(), ResultEnum.PARAM_CHECK, "请上传企业资质认证");
        if (Objects.isNull(request.getCompanyId())) {
            if (StringUtils.isBlank(request.getPassword())) {
                request.setPassword(getRandomPassword());
            }
            if(Objects.isNull(request.getIndustryId())) {
                request.setIndustryId(industryMapperExt.selectByName("经销商"));
            }
        }

        RequestContext requestContext = RequestContextHolder.getRequestContext();
        CardSaveRequest cardSaveRequest = CardSaveRequest.builder()
                .phone(request.getPhone())
                .style(request.getStyle())
                .name(request.getName())
                .personalWx(request.getPersonalWx())
                .logo(request.getLogo())
                .companyWx(request.getCompanyWx())
                .photo(request.getPhoto())
                .position(request.getPosition())
                .soundRecording(request.getSoundRecording())
                .soundTime(request.getSoundTime())
                .email(request.getEmail())
                .briefIntroduction(request.getBriefIntroduction())
                .companyId(request.getCompanyId())

                .password(request.getPassword())
                .companyName(request.getCompanyName())
                .companyLogo(request.getCompanyLogo())
                .companyNotice(request.getCompanyNotice())
                .industryId(request.getIndustryId())
                .licensePhotos(request.getLicensePhotos())

                .id(requestContext.getUser().getUserId())
                .companyKey(requestContext.getRequest().getCompanyKey())
                .token(requestContext.getRequest().getToken())
                .isClientJxs(true)
                .build();
        ResultModel resultModel = cardFeign.save(cardSaveRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success(true);
    }

    @PostMapping("isCreateCompany")
    @ApiOperation(value = "判断是否有名片或者公司")
    @SecurityAuthCheck
    public ResultModel<Boolean> isCreateCompany() {
        final RequestContext.User user = RequestContextHolder.getRequestContext().getUser();
        boolean hasCard = Objects.nonNull(user.getCompanyId()) && Objects.nonNull(user.getCardId());
        return ResultModel.success(hasCard);
    }

    @ApiOperation(value = "得到名片二维码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "名片id", required = true, paramType = "Integer"),
    })
    @PostMapping("getWxTwoCode")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel getWxTwoCode(@RequestAttribute BusinessCardRequest request) {
        SunCodeCardRequest sunCodeCardRequest = SunCodeCardRequest.builder().cardId(request.getCardId()).build();
        ResultModel<SunCodeCardResponse> sunCodeCardResponseResultModel = sunCodeFeign.card(sunCodeCardRequest);
        AssertUtil.isTrue(sunCodeCardResponseResultModel);
        String wxTwoCode = sunCodeCardResponseResultModel.getData().getCodeUrl();
        return ResultModel.success(wxTwoCode);
    }

    @ApiOperation(value = "验证名片是否过期")
    @PostMapping("/verifyExpired")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<Long> verifyExpired(@RequestAttribute CardVerifyExpiredRequest request) {
        ResultModel<CardCheckResponse> cardCheckResponseResultModel = cardFeign.check(CardCheckRequest.builder().cardId(request.getCardId()).build());
        AssertUtil.isTrue(cardCheckResponseResultModel);
        AssertUtil.isTrue(cardCheckResponseResultModel.getData().isEffective(), "名片已过期");
        return ResultModel.success(cardCheckResponseResultModel.getData().getDays());
    }

    @ApiOperation(value = "用户可接收微信推送次数")
    @PostMapping("/formIdCount")
    @SecurityAuthCheck
    public ResultModel<Integer> formIdCount() {
        return ResultModel.success(0);//crm改为APP，formId废弃
    }

    @ApiOperation(value = "清空微信推送次数")
    @PostMapping("/delFormId")
    @SecurityAuthCheck
    public ResultModel<Boolean> delFormId() {
        return ResultModel.success(true);//crm改为APP，formId废弃
    }

    @ApiOperation(value = "分享")
    @PostMapping("/share")
    @SecurityAuthCheck
    public ResultModel<CardShareResponse> share(@RequestAttribute CardShareRequest request) {

        BusinessCard businessCardModel = businessCardBaseService.getCustomer(request.getCardId());
        Company company = companyBaseService.getById(businessCardModel.getCompanyId());

        TemplateGet2Request createRequest = TemplateGet2Request.builder()
                .templateType(TemplateApi.Type.ID_CRM_APP_CARD)
                .cardId(request.getCardId())
                .build();
        ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get2(createRequest);
        AssertUtil.isTrue(getResponseResultModel);
        String cardMoments = getResponseResultModel.getData().getImageUrl();
        createRequest = TemplateGet2Request.builder()
                .templateType(TemplateApi.Type.ID_WECHAT_CARD)
                .cardId(request.getCardId())
                .build();
        getResponseResultModel = templateFeign.get2(createRequest);
        AssertUtil.isTrue(getResponseResultModel);
        String photoUrl = getResponseResultModel.getData().getImageUrl();

        AccountCompanyIdRequest accountCompanyIdRequest = AccountCompanyIdRequest.builder()
                .companyId(businessCardModel.getCompanyId())
                .loginEnum(LoginEnum.USER)
                .build();
        ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getCompanyIdDefaultIfNull(accountCompanyIdRequest);
        String wechatId = accountResponseResultModel.isSuccess() ? accountResponseResultModel.getData().getWechatId() : null;

        CardShareResponse response = CardShareResponse.builder()
                .cardMoments(cardMoments)
                .cardId(request.getCardId())
                .companyId(company.getCompanyId())
                .shareSpeech(businessCardModel.getShareSpeech())
                .companyName(company.getCompanyName())
                .position(businessCardModel.getPosition())
                .name(businessCardModel.getName())
                .wechatId(wechatId)
                .oneCompany(companyBaseService.isOneWechat(company.getCompanyId()))
                .photoUrl(photoUrl)
                .build();
        return ResultModel.success(response);
    }

    private String getRandomPassword() {
        return String.valueOf(rand.nextInt(99999 - 10000 + 1) + 10000);
    }
}
